package com.imooc.auth.controller;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.imooc.api.util.IPUtil;
import com.imooc.constant.RedisKeyConstant;
import com.imooc.grace.result.ResponseJSONResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/passport")
public class PassportController {

    private static  final Logger LOG = LoggerFactory.getLogger(PassportController.class);
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @GetMapping("/getSMSCode")
    public ResponseJSONResult getSMSCode(String mobile, HttpServletRequest request){
        if (StrUtil.isBlank(mobile)) return ResponseJSONResult.errorMsg("传入参数错误");

        // 限制用户只能在60秒内发送一次
        String ip = IPUtil.getRequestIp(request);
        // 存入redis中，然后在拦截器中限制发送短信只能为60秒一次
        stringRedisTemplate.opsForValue().setIfAbsent(RedisKeyConstant.MOBILE_SMS_CODE + ip, mobile, 60, TimeUnit.SECONDS);



        String code = RandomUtil.randomNumbers(6);
        LOG.debug("发送的验证码是：{}", code);
        // 1 把验证码存入redis中
        stringRedisTemplate.opsForValue().set(RedisKeyConstant.MOBILE_SMS_CODE + mobile, code, 30*60, TimeUnit.SECONDS);
        return ResponseJSONResult.ok();
    }
}
